var mongoose = require('mongoose')
  , Post = mongoose.model('Post')
  , User = mongoose.model('User')
  , async = require('async')
//post
exports.new = function(req, res){
	res.render('post', { 
	   title: '发表',
	   user: req.session.user,
	   success: req.flash('success').toString(),
	   error: req.flash('error').toString()
	});
};

exports.create = function(req, res){
  	var post = new Post();
  	post.title = req.body.title.trim();
  	post.content = req.body.content;
  	post.tags = [req.body.tag1, req.body.tag2, req.body.tag3];
    post.user = req.session.user._id;
    post.avatar = req.session.user.avatar;
    //console.log(post);
  	post.save(function(err){
  		if (err) {
  			req.flash('error', err);
  			return res.redirect('/posts/new');
  		};
      req.flash('success', '发布成功!');
  		res.redirect('/');
  	});
};

exports.show = function(req, res){
    var options = { _id: req.params.id};  
    Post.loadByOp(options, function(err, post){
        if (err) {
          req.flash('error', err);
          return res.redirect('/');
        };
        post.pv += 1;
        post.save(function(){
            res.render('article', {
              title: post.title,
              post: post,
              user: req.session.user,
              success: req.flash('success').toString(),
              error: req.flash('error').toString()
            });
        });
        
    });

};

exports.listByUser = function(req, res){
    async.waterfall([
        function(callback){
            User.loadByOp({username: req.params.username}, function(err, user){
                if (err) {
                  req.flash('error', err);
                  return res.redirect('/');
                }
                if (!user) {
                  req.flash('error', '用户不存在!');
                  return res.redirect('/');
                }
                callback(null, user);
            });
        },
        function(user, callback){
            var options = { user: user._id };  
            Post.listByOp(options, function(err, posts){
                if (err) {
                  req.flash('error', err);
                  return res.redirect('/');
                }
                callback(null, posts);
            });
        }
    ], function(err, result){
        if (err) {
          req.flash('error', err);
          return res.redirect('/');
        }
        res.render('user', {
          title: req.params.username,
          posts: result,
          user: req.session.user,
          success: req.flash('success').toString(),
          error: req.flash('error').toString()
        });
    });
    

};

exports.edit = function(req, res){
    var options = { _id: req.params.id, user: req.session.user._id };  
    Post.loadByOp(options, function(err, post){
        if (err) {
          req.flash('error', err);
          return res.redirect('back');
        };
        res.render('post', {
          title: post.title,
          post: post,
          user: req.session.user,
          success: req.flash('success').toString(),
          error: req.flash('error').toString()
        });
    });

};

exports.update = function(req, res){
    var options = { _id: req.params.id, user: req.session.user._id };  
    Post.loadByOp(options, function(err, post){
        if (err) {
          req.flash('error', err);
          return res.redirect('/posts/'+req.params.id);
        };
        post.content = req.body.content;
        post.save(function(err){
            if (err) {
                req.flash('error', err);
                return res.redirect('/posts/'+req.params.id);
            };
            req.flash('success', '修改成功!');
            res.redirect('/posts/'+req.params.id);
        });
    });

};

exports.destroy = function(req, res){
    var options = { _id: req.params.id, user: req.session.user._id };  
    Post.loadByOp(options, function(err, post){
        if (err) {
          req.flash('error', err);
          return res.redirect('back');
        };
        post.remove(function(err){
            if (err) {
                req.flash('error', err);
                return res.redirect('back');
            };
            req.flash('success', '删除成功!!');
            res.redirect('/');
        });
    });

};


exports.index = function(req, res){
    var page = (req.query.page > 0 ? req.query.page : 1) - 1;
    var perPage = 10;
    var options = {
      perPage: perPage,
      page: page
    }
    Post.list(options, function(err, posts){
      if (err) {
          req.flash('error', err);
          return res.redirect('/');
      }
      //console.log(posts);
      Post.count().exec(function(err, count){
        res.render('archive', {
            title: '存档',
            posts: posts,
            // page: page + 1,
            // pages: count > 0 ? Math.ceil(count / perPage) : 1,
            page: page + 1,
            isFirstPage: page == 0,
            isLastPage: (page * perPage + posts.length) == count,
            user: req.session.user,
            success: req.flash('success').toString(),
            error: req.flash('error').toString(),
        });
      });
    });
};

exports.getTags = function(req, res){
    Post.find().distinct('tags', function(err, tags){
    		if (err) {
    			req.flash('error', err);
    			return res.redirect('/');
    		};
    		res.render('tags', {
    			title: '标签',
    			tags: tags,
    			user: req.session.user,
    			success: req.flash('success').toString(),
    			error: req.flash('error').toString()
    		});
  	});

};

exports.getTag = function(req, res){
    Post.listByOp({tags: req.params.tag}, function(err, posts){
        if (err) {
          req.flash('error', err);
          return res.redirect('/');
        };
        res.render('tag', {
          title: 'TAG:' + req.params.tag,
          posts: posts,
          user: req.session.user,
          success: req.flash('success').toString(),
          error: req.flash('error').toString()
        });
    });

};

exports.search = function(req, res){
    var options = { title: new RegExp(req.query.keyword, 'gi')};  
    Post.listByOp(options, function(err, posts){
        console.log(err);
        if (err) {
          req.flash('error', err);
          return res.redirect('/');
        };
        res.render('search', {
          title: "SEARCH:" + req.query.keyword,
          posts: posts,
          user: req.session.user,
          success: req.flash('success').toString(),
          error: req.flash('error').toString()
        });
    });

};

exports.reprint = function(req, res){
    
    Post.loadByOp({_id: req.params.id}, function(err, post){
        if (err) {
          req.flash('error', err);
          return res.redirect('back');
        };
        var currentUser = req.session.user,
            reprint_from = { user: post.user, title: post.title, createdAt: post.createdAt }, 
            reprint_to = { user: currentUser, avatar: currentUser.avatar };

        //var op = {user: reprint_from.user, title: reprint_from.title, createdAt: reprint_from.createdAt}
        //post.reprint_from = reprint_from;
        //post.save();


        var repost = new Post();
        repost.title = "[转载]" + post.title;
        repost.content = post.content;
        repost.tags = post.tags;
        repost.user = reprint_to.user;
        repost.avatar = reprint_to.avatar;
        repost.reprint_info = {'reprint_from': reprint_from}
        repost.save(function(err){
            if (err) {
              req.flash('error', err);
              return res.redirect('back');
            };
            res.flash('success', '');
            res.redirect('posts/' + reqpost._id);
        })
    });

};